package com.example.demo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.websocket.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@ClientEndpoint
public class MainTest {
    private Session session;
    private CountDownLatch latch = new CountDownLatch(1);
    private String lastMessage;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("✅ 连接已建立，连接到: " + session.getRequestURI());
        latch.countDown(); // 通知主线程连接成功
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("📨 收到消息: " + message);
        this.lastMessage = message;
        // 这里可以处理收到的消息，比如解析JSON等
        try {
            int i = Integer.parseInt(message);
            System.out.println(sendSzdxlxDir.getCurSj() + "<==onMessage==>" + i);
            if (i < 7200) {
                sendSzdxlxDir.setCurSj(i);
            }
        } catch (Exception e) {
            END = true;
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("❌ 连接关闭: " + closeReason.getReasonPhrase());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("💥 发生错误:");
        throwable.printStackTrace();
    }

    // 发送消息的方法
    public void sendMessage(String message) throws IOException {
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
            System.out.println("📤 已发送: " + message);
        } else {
            System.err.println("无法发送消息，会话未打开");
        }
    }

    // 等待连接建立
    public boolean awaitConnection(long timeout, TimeUnit unit) throws InterruptedException {
        return latch.await(timeout, unit);
    }

    // 获取最后一次收到的消息（用于测试或简单交互）
    public String getLastMessage() {
        return lastMessage;
    }

    // 关闭连接
    public void close() throws IOException {
        if (session != null) {
            session.close();
        }
    }

    private static String PHPSESSID;
    private static boolean END = false;
    private static final List<SzdxlxDir> szdxlxDirs = new ArrayList<>();
    private static final int JG = 6;
    private static SzdxlxDir curSzdxlxDir;
    private static SzdxlxDir sendSzdxlxDir;

    private static void nextSzdxlxDir() {
        for (SzdxlxDir szdxlxDir : szdxlxDirs) {
            if (szdxlxDir.getCurSj() != szdxlxDir.getMaxSj()) {
                curSzdxlxDir = szdxlxDir;
                break;
            }
        }
    }

    private static SSLSocketFactory sslSocketFactory;

    static {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, new java.security.SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Hello World");
        String jarPath = MainTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println("Jar path: " + jarPath);
        String dir = StrUtil.subBefore(jarPath, "/", true);
        JSONObject userConfig = JSON.parseObject(FileUtil.readString(dir + "/config.json", StandardCharsets.UTF_8));
        System.out.println(userConfig);


        HttpRequest post = HttpUtil.createPost("https://stu.5zk.com.cn/zk8exam/check_login.php");
        post.setSSLSocketFactory(sslSocketFactory);
        post.form("admin_name", userConfig.getString("username"));
        post.form("admin_password", userConfig.getString("password"));
        post.form("s_or_t", "1");
        HttpResponse response = post.execute();
        System.out.println(response.getStatus());
        PHPSESSID = response.getCookieValue("PHPSESSID");
        HttpRequest get = HttpUtil.createGet("https://stu.5zk.com.cn/zk8exam/mycourse.php");
        get.setSSLSocketFactory(sslSocketFactory);
//        String cookie = "PHPSESSID=22ha0q859d6fpoa2kugdm7itgk";
        String cookie = "PHPSESSID=" + PHPSESSID;
        get.cookie(cookie);
        System.out.println(cookie);
//        get.cookie(response.getCookies());
//        System.out.println(body);
        Elements elements = Jsoup.parse(get.execute().body()).select(".block tr > td:first-child a");
        for (Element element : elements) {
            String kcdm = element.text();
            System.out.println(kcdm);
            get = HttpUtil.createGet("https://stu.5zk.com.cn/zk8exam/jp_wiki_study.php?kcdm=" + kcdm);
            get.setSSLSocketFactory(sslSocketFactory);
            get.cookie(cookie);
            Document documentKc = Jsoup.parse(get.execute().body());
            Element userlogIdEle = documentKc.getElementById("userlog_id");
            if (userlogIdEle == null){
                continue;
            }
            System.out.println("获取到 userlog_id：" + userlogIdEle.val());
            String typeId = documentKc.getElementById("TypeId").val();
            System.out.println("获取到 typeId：" + typeId);

            Elements elementsKcs = documentKc.select(" .block-content ul li ");
            for (Element elementsKc : elementsKcs) {
                String attr = elementsKc.selectFirst("a").attr("href");
                String jjwikiid = StrUtil.subAfter(attr, "=", true);
//            System.out.println("视频id：" + jjwikiid);

                String div = elementsKc.select("div").get(1).text();

                String[] curTimeArr = StrUtil.subBetween(div, "(", "/").split(":");
                int curTotal = Integer.parseInt(curTimeArr[0]) * 3600 + Integer.parseInt(curTimeArr[1]) * 60 + Integer.parseInt(curTimeArr[2]);
//            System.out.println("获取到当前观看视频时长：" + curTotal);

                String[] timeArr = StrUtil.subBetween(div, "/", ")").split(":");
                int total = Integer.parseInt(timeArr[0]) * 3600 + Integer.parseInt(timeArr[1]) * 60 + Integer.parseInt(timeArr[2]);
//            System.out.println("获取到视频时长：" + total);

                SzdxlxDir szdxlxDir = new SzdxlxDir();
                szdxlxDir.setKcdm(kcdm);
                szdxlxDir.setJjwikiid(jjwikiid);
                szdxlxDir.setCurSj(curTotal);
                szdxlxDir.setMaxSj(total);
                szdxlxDir.setTypeId(typeId);
                szdxlxDirs.add(szdxlxDir);
            }
        }
        System.out.println("拉取到课程视频数量：" + szdxlxDirs.size());

        nextSzdxlxDir();

        loadUserlog();

        // 要连接的 WebSocket 服务地址 (以 wss://echo.websocket.org 为例，这是一个公共测试服务)
        String serverUrl = "wss://sdckwss.5zk.com.cn/sdck_jjsp?session_id=" + PHPSESSID;
        MainTest clientEndpoint = new MainTest();
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            System.out.println("🔄 正在连接到: " + serverUrl);
            // 连接服务器
            container.connectToServer(clientEndpoint, new URI(serverUrl));
            // 等待连接建立（最多等5秒）
            if (clientEndpoint.awaitConnection(5, TimeUnit.SECONDS)) {
                System.out.println("✅ 成功连接到服务器！");
                while (!END) {
                    Thread.sleep(JG * 1000L);
                    curSzdxlxDir.setCurSj(Math.min(curSzdxlxDir.getMaxSj(), curSzdxlxDir.getCurSj() + JG));
                    sendSzdxlxDir = curSzdxlxDir;
                    clientEndpoint.sendMessage("Update1: jjwikiid=" + curSzdxlxDir.getJjwikiid() + "&TypeId=" + curSzdxlxDir.getTypeId() + "&cur_jindu=" + curSzdxlxDir.getCurSj() + "&userlog_id=" + curSzdxlxDir.getUserLogId());
                    if (curSzdxlxDir.getCurSj() >= curSzdxlxDir.getMaxSj()) {
                        nextSzdxlxDir();
                        if (curSzdxlxDir != null) {
                            loadUserlog();
                        } else {
                            END = true;
                        }
                    }
                }
            } else {
                System.err.println("连接超时");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void loadUserlog() {
        String url = "https://stu.5zk.com.cn/zk8exam/jp_wiki_study.php?kcdm=" + curSzdxlxDir.getKcdm() + "&jjwikiid=" + curSzdxlxDir.getJjwikiid();
        System.out.println(url);
        HttpRequest get = HttpUtil.createGet(url);
        get.setSSLSocketFactory(sslSocketFactory);
        get.cookie("PHPSESSID=" + PHPSESSID);
        Document document = Jsoup.parse(get.execute().body());
        curSzdxlxDir.setUserLogId(document.getElementById("userlog_id").val());
        System.out.println("获取到userlog_id：" + curSzdxlxDir.getUserLogId());
    }
}
